<?php
namespace app\service;

class FaceAuth
{
# 微信支付
    public $api_key = '';
    public $api_secret = '';
 
    public function __construct(){
        $this->api_key = getenv('FACE_PLUS_KEY') ?? 'DhLHW1F_zonEPwO6hdbp4PP1CeBEf7Q-';
        $this->api_secret = getenv('FACE_PLUS_SECRET') ?? 'pe4Bnhxyb2rs8rZJaKSBbmrg5V6Eo9Mg';
    }

    public function compare($image_url1, $image_url2)
    {
        $api_url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
        $data = [
            'api_key' => $this->api_key,
            'api_secret' => $this->api_secret,
            'image_url1' => $image_url1,
            'image_url2' => $image_url2,
        ];
        $result = $this->http_Request($api_url, [], $data);

        $result = json_decode($result, true);
        // var_dump($result);exit;
        // var_dump($result['confidence']);exit;
        if(isset($result['error_message'])){
            return $this->failDetail($result['error_message']);
        }
        if($result['confidence'] < 60){
            return '图片与真人认证图人脸不匹配';
        }
        return 0;
    }
    private function getAccessToken(){
        $cachekey = 'baiduapitoken';
        $cacheToken = cache($cachekey);
        if ($cacheToken) return $cacheToken;
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => getenv('BAIDU_AUDIO_APP_KEY'),
            'client_secret' => getenv('BAIDU_AUDIO_SECRET_KEY')
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        if ($rtn->expires_in && $rtn->access_token) {
            cache($cachekey, $rtn->access_token, $rtn->expires_in);
        }
        return $rtn->access_token;
    }
    public function comparebaidu($image_url1, $image_url2)
    {
        $url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token={$this->getAccessToken()}";
        $params = [
            [
                'image'=>$image_url1,
                'image_type'=>'URL',
                'face_type'=>'LIVE',
                'quality_control'=>'LOW',
                'liveness_control'=>'NORMAL',
            ],
            [
                'image'=>$image_url2,
                'image_type'=>'URL',
                'face_type'=>'CERT'
            ],
        ];
        $result = http_post($url, $params);

        // var_dump($result);exit;
        if (!$result || $result['error_code'] != 0) {
            return '人脸匹配异常';
        }
        if ($result['result']['score'] < 80) {
            return '人脸匹配失败';
        }
        return 0;
    }

    public function failDetail($errcode)
    {
        $reason = [
            "AUTHENTICATION_ERROR"=>"api_key和api_secret不匹配。",
            "CONCURRENCY_LIMIT_EXCEEDED"=>"并发数超过限制。",
            "INTERNAL_ERROR"=>"服务器内部错误",
        ];
        if (isset($reason[$errcode])) {
            return $reason[$errcode];
        }
        return '未知原因';
    }

    /**
     * 数据请求
     * @param $url
     * @param array $header 获取头部
     * @param string $post_data POST数据，不填写默认以GET方式请求
     * @return bool|string
     */
    public function http_Request($url, $header = array(), $post_data = "")
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 2);
        if ($post_data != "") {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //设置post提交数据
        }
        //判断当前是不是有post数据的发
        $output = curl_exec($ch);
        if ($output === FALSE) {
            $output = "curl 错误信息: " . curl_error($ch);
        }
        curl_close($ch);
        return $output;
    }
}
?>